﻿window.format = function (b, a) {
    if (!b || isNaN(+a)) return a; var a = b.charAt(0) == "-" ? -a : +a, j = a < 0 ? a = -a : 0, e = b.match(/[^\d\-\+#]/g), h = e && e[e.length - 1] || ".", e = e && e[1] && e[0] || ",", b = b.split(h), a = a.toFixed(b[1] && b[1].length), a = +a + "", d = b[1] && b[1].lastIndexOf("0"), c = a.split("."); if (!c[1] || c[1] && c[1].length <= d) a = (+a).toFixed(d + 1); d = b[0].split(e); b[0] = d.join(""); var f = b[0] && b[0].indexOf("0"); if (f > -1) for (; c[0].length < b[0].length - f; ) c[0] = "0" + c[0]; else+c[0] == 0 && (c[0] = ""); a = a.split("."); a[0] = c[0]; if (c = d[1] && d[d.length -
1].length) { for (var d = a[0], f = "", k = d.length % c, g = 0, i = d.length; g < i; g++) f += d.charAt(g), !((g - k + 1) % c) && g < i - c && (f += e); a[0] = f } a[1] = b[1] && a[1] ? h + a[1] : ""; return (j ? "-" : "") + a[0] + a[1]
};

jQuery.fn.Checked = function (value) {
    if (value == null || value == undefined) {
        return $(this).attr('value');
    }
    else {
        var _p = $(this).find('p')[1];
        if (value == '0') {
            $(this).attr('value', '1');
            $(_p).removeClass('m_checkbox_uncheck');
            $(_p).addClass('m_checkbox_checked');
        }
        else {
            $(this).attr('value', '0');
            $(_p).removeClass('m_checkbox_checked');
            $(_p).addClass('m_checkbox_uncheck');
        }
    }
}

function show_dataview(val) {
    if (val == 0) {
        $('#data_view').css('display', 'block');
        $('#data_options').css('display', 'none');
    }
    else {
        $('#data_view').css('display', 'none');
        $('#data_options').css('display', 'block');
    }
}

function logout() {
    $.ajax({
        url: "/Home/Logout/",
        dataType: "json",
        cache: false,
        type: 'GET',
        data: {},
        success: function (result) {
            if (result.Success) {
                $('#log_auth').val('0');
                window.location.href = window.location.href;
            }
        }
    });
}

function LoginStatus() {
    $.ajax({
        url: "/Home/LoginStatus/",
        dataType: "json",
        cache: false,
        type: 'GET',
        data: {},
        success: function (result) {
            $('#log_auth').val((result.Success) ? '1' : '0');
        }
    });
}

function collapse_close_all(_obj) {
    $(_obj).children().each(function () {
        collapse_close($(this));
    });
}
function collapse_close(element) {
    var _obj = $(element).find('div')[0];

    $(element).attr('collaps', 'closed');
    $(_obj).css('display', 'none');

    var _h3 = $(element).find('h3')[0];
    var _span = $(_h3).find('span')[0];
    $(_span).css("background", "url('Content/Themes/Images/icons-18-white.png') -179px 0 no-repeat #ccc");
}
function collapse_open(element) {
    var _obj = $(element).find('div')[0];

    $(element).attr('collaps', 'opened');
    $(_obj).css('display', 'block');

    var _h3 = $(element).find('h3')[0];
    var _span = $(_h3).find('span')[0];
    $(_span).css("background", "url('Content/Themes/Images/icons-18-white.png') -215px 0 no-repeat #333");
}

function radio_uncheck_all(parent) {
    $(parent).children('div').each(function () {
        $(this).attr('value', '0');

        var _h3 = $(this).find('h3')[0];
        var _first_span = $(_h3).find('span')[0];

        $($(_first_span).children('span')[0]).css('display', 'inline-block');
        $(_first_span).css("background", "#ddd");
    });
}

function radio_checked(element) {
    var _h3 = $(element).find('h3')[0];
    var _first_span = $(_h3).find('span')[0];

    $($(_first_span).children('span')[0]).css('display', 'none');
    $(_first_span).css("background", "url('Content/Themes/Images/icons-18-white.png') -251px 0 no-repeat #333");

    $(element).attr('value', '1');
}

jQuery.fn.RadioChecked = function () {
    radio_uncheck_all($(this).parent());
    radio_checked($(this));
}

function init() {
    $('.m_checked_box').bind('click', function () {
        $(this).Checked($(this).attr('value'));
    });

    $('.m_collap_item').bind('click', function (e) {
        if ($(this).attr('collaps') == 'closed') {
            collapse_close_all($(this).parent());
            collapse_open($(this));
        }
    });

    $('.ops_item').bind('click', function (e) {
        if ($(this).attr('value') == '1') return;
        radio_uncheck_all($(this).parent());
        radio_checked($(this));
    });

    var today = new Date();
    
    $('#numYear').val(today.getFullYear());
    $('#op_month').val((today.getMonth()+1) + '/' + today.getFullYear());
    
    $('#f_date').val(today.getDate() + '/' + (today.getMonth() +1) + '/' + today.getFullYear());
    $('#t_date').val(today.getDate() + '/' + (today.getMonth() +1) + '/' + today.getFullYear());
}

function OpsSelected() {
    var _type = '', _from = '', _to = '', _val = '';

    $('#ops_user').children('div').each(function () {
        _val = $(this).attr('value');

        if (_val == '1') {
            _type = $(this).attr('optype');

            if (_type == 'month')
                _from = $('#op_month').val();
            else if (_type == 'year')
                _from = $('#numYear').val();
            else if (_type == 'fromto') {
                _from = $('#f_date').val();
                _to = $('#t_date').val();
            }
        }
    });

    return { optype: _type, opfrom: _from, opto: _to };
}
//index
$(document).ready(function () {
    init();

    GetValueCookie();
    LoginStatus();
    $('#remember').Checked('0');
    $('#op_today').RadioChecked();

    $('#op_month').datepicker({
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'mm/yy',
        onClose: function (dateText, inst) {
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $(this).datepicker('setDate', new Date(year, month, 1));
        },
        beforeShow: function (input, inst) {
            if ((datestr = $(this).val()).length > 0) {
                year = datestr.split('/')[1];

                month = datestr.split('/')[0];
              
                $(this).datepicker('option', 'defaultDate', new Date(year, month-1, 1));
                $(this).datepicker('setDate', new Date(year, month-1, 1));
            }
        }
    });

    $('#numYear').spinner();
    $('#f_date').datepicker({ dateFormat: 'dd/mm/yy' });
    $('#t_date').datepicker({ dateFormat: 'dd/mm/yy' });

    checklogin();

    $('#options').css('display', 'none');
});


function DoLogin() {
    //$.mobile.showPageLoadingMsg()
    $('#mydiv').css('display', 'block');

    $.ajax({
        url: "/Home/Login/",
        dataType: "json",
        cache: false,
        type: 'POST',
        data: { User: $('#txtuser').val(), Pwd: $('#txtpwd').val(), ID1: $('#txtid1').val(), ID2: $('#txtid2').val(), Remember: $('#remember').Checked() },
        success: function (result) {
            if (result.Success == true) {
                $('#mydiv').css('display', 'block');
                $('#log_auth').val('1');
                checklogin();
            }
            else {
                $('#mydiv').css('display', 'none');
                $("#dialog-message").dialog({
                    modal: true,
                    buttons: {
                        Ok: function () {
                            $(this).dialog("close");
                        }
                    }
                });
            }
            //$.mobile.hidePageLoadingMsg();
        }
    });
}

function checklogin() {
    if ($('#log_auth').val() == '0') {
        $('#login_Container').attr('style', 'display:block');
        $('#data_View').attr('style', 'display:none');
    }
    else {
        $('#login_Container').attr('style', 'display:none');
        $('#data_View').attr('style', 'display:block');
        GetReport();
    }
}

function GetValueCookie() {
    var value = getCookie("UserCafe");

    if (typeof (value) != undefined && value != "" && value != null) {
        $('#txtuser').val(value.split('|')[0]);
        $('#txtid1').val(value.split('|')[1]);
        $('#txtid2').val(value.split('|')[2]);
        //$('#remember').attr('checked', 'checked');
    }
    else
        $('#remember').Checked('1');
}

function GetReport() {
    $.ajax({
        url: "/Home/GetReport/",
        dataType: "json",
        cache: false,
        type: 'GET',
        data: {},
        success: function (result) {
            if (result.Success) {
                AppendProfitRevenue(result.data);
                AppendQty(result.data);
                AppendCost(result.data);
            }
            else {
                detail_val = 'Error'
            }
        }
    });
}

function AppendProfitRevenue(data) {

    var _html = "<table class='data_table'>";
    var _html_Revenue = "<table class='data_table'>";
    var _grp = "", _tt1 = 0, _tt2 = 0;
    $.each(data.Pvs, function (index, item) {
        if (_grp != item.GroupName) {
            _grp = item.GroupName;
            _html += "<tr class='grp_title'><td>" + item.GroupName + "</td><td></td><td></td></tr>";
            _html_Revenue += "<tr class='grp_title'><td>" + item.GroupName + "</td><td></td><td></td></tr>";
        }
        _tt1 += item.Profit;
        _tt2 += item.Revenue;
        _html += "<tr><td class='col_name'>" + item.Name + "</td><td class='col_unit'>" + item.Unit + "</td><td class='col_money'>" + format('#,###.##', item.Profit) + "</td></tr>";
        _html_Revenue += "<tr><td class='col_name'>" + item.Name + "</td><td class='col_unit'>" + item.Unit + "</td><td class='col_money'>" + format('#,###.##', item.Revenue) + "</td></tr>";
    });
    _html += "</table>";
    _html_Revenue += "</table>";

    $('#loinhuan').html(_html);
    $('#doanhthu').html(_html_Revenue);
    $('#tt_profit').html(format('#,###.##', _tt1));
    $('#tt_revenue').html(format('#,###.##', _tt2));
}

function AppendQty(data) {
    var _html = "<table class='data_table'>";
    var _grp = "", _tt1 = 0;
    $.each(data.Quantitys, function (index, item) {
        if (_grp != item.GroupName) {
            _grp = item.GroupName;
            _html += "<tr class='grp_title'><td>" + item.GroupName + "</td><td></td><td></td></tr>";
        }
        _tt1 += item.Qty;
        _html += "<tr><td class='col_name'>" + item.Name + "</td><td class='col_unit'>" + item.Unit + "</td><td class='col_money'>" + format('#,###.##', item.Qty) + "</td></tr>";
    });
    _html += "</table>";

    $('#soluong').html(_html);
    $('#tt_qty').html(format('#,###.##', _tt1));
}

function AppendCost(data) {
    if (data.Costs.length <= 0) return;
    var isDetail = data.Costs[0].IsDetail;

    var _html = "<table class='data_table'>";
    var _grp = "", _tt = 0;

    $.each(data.Costs, function (index, item) {
        if (isDetail == 1) {
            if (_grp != item.GroupName) {
                _grp = item.GroupName;
                _html += "<tr class='grp_title'><td>" + item.Date + "</td><td></td><td></td></tr>";
            }
            _html += "<tr><td>" + item.Descr + "</td><td>" + item.TypeDescr + "</td><td class='col_money'>" + format('#,###.##', item.Money) + "</td></tr>";
        }
        else
            _html += "<tr><td class='col_date'>" + item.Date + "</td><td>" + item.Descr + "</td><td class='col_money'>" + format('#,###.##', item.Money) + "</td></tr>";
        _tt += item.Money;
    });
    _html += "</table>";
    $('#chiphi').html(_html);
    $('#tt_cost').html(format('#,###.##', _tt));
}

function ops_accept_changed() {
    var result = new OpsSelected();

    $.ajax({
        url: "/Home/OptionsChanged/",
        dataType: "json", cache: false, type: 'GET',
        data: { optype: result.optype, opfrom: result.opfrom, opto: result.opto },
        success: function (result) {
            if (result.Success) {
                GetReport();
                showHome();
            }
            else {
                detail_val = 'Error'
            }
        }
    });
}

function showHome() {
    $('#Data_Group').css('display', 'block');
    $('#options').css('display', 'none');
    $('#btn_ops').attr('class', '');
    $('#btn_home').attr('class', 'top_bar_item_normal');
}

function showOps() {
    $('#Data_Group').css('display', 'none');
    $('#options').css('display', 'block');
    $('#btn_ops').attr('class', 'top_bar_item_normal');
    $('#btn_home').attr('class', '');
}

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}